let jwt = require('jsonwebtoken');

module.exports = () => {
    return async (ctx,next) => {
        //1.排除不需要校验的接口
        let writePath = ['/api/login'];
        if(writePath.includes(ctx.path)){
            //不需要校验
            await next();
        }else{
            //需要校验
            //2.获取token
            let token = ctx.get('token');
            try{
                jwt.verify(token,'lixd'); //如果能校验成功
                await next();
            }catch(e){
                //没有通过校验
                //3.是token产生错误还是其他的错误
                if(e.name === 'TokenExpiredError' || e.name === 'JsonWebTokenError'){
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:'token有误'
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }
    }
}